use sqlx::SqlitePool;

use crate::model::Todo;

pub async fn save_todo(pool: &SqlitePool, title: &str) -> Result<Todo, sqlx::Error> {
    let now = chrono::Local::now();

    let todo = sqlx::query_as!(
        Todo,
        r#"
    INSERT INTO todo(title,active,create_at) VALUES(?,?,?)
    RETURNING id,title,active,create_at,update_at
    "#,
        title,
        true,
        now
    )
    .fetch_one(pool)
    .await?;

    Ok(todo)
}

pub async fn get_todos_by_active(
    pool: &SqlitePool,
    active: bool,
) -> Result<Vec<Todo>, sqlx::Error> {
    let todos = sqlx::query_as!(
        Todo,
        r#"
    SELECT id,title,active,create_at,update_at FROM todo
    WHERE active=?
    ORDER BY create_at desc
    "#,
        active
    )
    .fetch_all(pool)
    .await?;

    Ok(todos)
}

pub async fn update_todo(
    pool: &SqlitePool,
    todo_id: i64,
    active: bool,
) -> Result<Todo, sqlx::Error> {
    let todo = sqlx::query_as!(
        Todo,
        r#"
    UPDATE todo SET active=?
    WHERE id=?
    RETURNING id,title,active,create_at,update_at
    "#,
        active,
        todo_id
    )
    .fetch_one(pool)
    .await?;

    Ok(todo)
}
